<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\Traits\RetrunService;

class BaseRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected $strings_val = [
        'required' => '为必填项',
        'min' => '最小为:min',
        'max' => '最大为:max',
        'between' => '长度在:min和:max之间',
        'integer' => '必须为整数',
        'exists' => '不存在',
        'unique' => '已存在',
    ];

    //返回给前台的错误信息
    public function messages()
    {
        $rules = $this->rules();
        $array = [];
        if (count($rules) > 0) {
            $k_array = $this->strings_key;
            $v_array = $this->strings_val;
            foreach ($rules as $key => $value) {
                $new_arr = explode('|', $value);//分割成数组
                foreach ($new_arr as $k => $v) {
                    $head = strstr($v, ':', true);//截取:之前的字符串
                    if ($head) {
                        $v = $head;
                    }
                    $array[$key . '.' . $v] = $k_array[$key] . $v_array[$v];
                }
            }
        }
        return $array;
    }

    public function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->all();
        $error = $error[0] ?? '';

        throw (new HttpResponseException(RetrunService::fail($error)));
    }
}
